package com.qianli.cashmama.product.server.controller.pay2;


import com.alibaba.fastjson.JSON;
import com.alibaba.nacos.api.config.annotation.NacosValue;
import com.fqgj.log.factory.LogFactory;
import com.fqgj.log.interfaces.Log;
import com.google.common.collect.Maps;
import com.jsoniter.JsonIterator;
import com.jsoniter.any.Any;
import com.jsoniter.output.JsonStream;
import com.qianli.cashmama.product.server.controller.pay.*;
import com.qianli.cashmama.product.server.controller.pay2.http.HttpResult;
import com.qianli.cashmama.product.server.controller.pay2.http.PooledHttpService;
import com.qianli.cashmama.product.server.dao.PayCallbackLogDao;
import com.qianli.cashmama.product.server.dao.PayRequestLogDao;
import com.qianli.cashmama.product.server.entity.ClReceiverDetailEntity;
import com.qianli.cashmama.product.server.entity.PayCallbackLogEntity;
import com.qianli.cashmama.product.server.entity.PayRequestLogEntity;
import com.qianli.cashmama.product.server.job.PayCallBackToBizJob;
import com.qianli.cashmama.product.server.job.SendToMerchantData;
import com.robert.vesta.util.IdUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.io.IOException;
import java.math.BigDecimal;
import java.security.MessageDigest;
import java.util.Arrays;
import java.util.Map;
import java.util.Set;

@RestController
@RequestMapping("/pay/tiger")
public class TigerPayController {

    private static final Log LOGGER = LogFactory.getLog(TigerPayController.class);

    @NacosValue(value = "${tiger.pay.key:ZXfGXGSuxdvgA4RvNsdphSAx2dcRxhTp}", autoRefreshed = true)
    private String tigerPayKey;

    @NacosValue(value = "${tiger.pay.productId:98727589}", autoRefreshed = true)
    private String productId;

    @NacosValue(value = "${tiger.pay.notifyUrl:http://147.139.37.96:9101/pay/callback}", autoRefreshed = true)
    private String notifyUrl;


    @NacosValue(value = "${tiger.pay.openapi:https://www.sharepay.solutions/openapi}", autoRefreshed = true)
    private String openapi;


    @Autowired
    private PayRequestLogDao payRequestLogDao;

    @Autowired
    private PayCallbackLogDao payCallbackLogDao;

    @Autowired
    private PayCallBackToBizJob payCallBackToBizJob;

    @Resource
    private PooledHttpService pooledHttpService;

    public static void main(String[] args) {
        RepayRequest a = new RepayRequest();
        a.setExtraInfo("");
        a.setOrderNo("adfasdfa");

    }

    //创建订单
    @RequestMapping("/pay/url")
    public OpenApiResponse create(@RequestBody SendToMerchantData request) {
        LOGGER.info("==tigerpay 请求支付链接 ==,request1:{}", JSON.toJSON(request));
        String bizData = request.getBizData();
        if (StringUtils.isEmpty(bizData)) {
            return new OpenApiResponse(400, "start repayment exception2");
        }
        RepayRequest deserialize1 = JsonIterator.deserialize(bizData, RepayRequest.class);

        Any deserialize = JsonIterator.deserialize(deserialize1.getExtraInfo());
        String userName = "default";
        ClReceiverDetailEntity clReceiverDetailEntity = payCallbackLogDao.getOneByMobile(deserialize.get("tel").toString());
        if (clReceiverDetailEntity != null) {
            userName = clReceiverDetailEntity.getName();
        }
        if(StringUtils.isEmpty(userName)){
            userName = "default";
        }
        String orderNoFor3d = IdUtils.genId() + "";
        PayRequestLogEntity payRequestLogEntity = new PayRequestLogEntity()
                .setTradeNo(deserialize1.getOrderNo())
                .setOrderNo(orderNoFor3d)
                .setOrderAmount(new BigDecimal(deserialize.get("orderAmount").toString()))
                .setTel(deserialize.get("tel").toString())
                .setUserName(userName);

        payRequestLogDao.insert(payRequestLogEntity);
        PayRequestLogEntity payRequestLogEntity1 = payRequestLogDao.selectByTripleOrderNo(orderNoFor3d);

        try {
            PaymentParam param = getCreateParam(payRequestLogEntity1);
            LOGGER.info("==tigerpay 访问支付链接接口 ==,params:{}", JsonStream.serialize(param));
            try {
                HttpResult httpResult = pooledHttpService.doPost(openapi + "/payment/create", JSON.toJSONString(param));
                LOGGER.info("==tigerpay 访问支付链接接口2 ==,res:{}", JsonStream.serialize(httpResult));

                TigerPayRequestResponse tigerPayRequestResponse = JSON.parseObject(httpResult.getData(), TigerPayRequestResponse.class);

                payRequestLogEntity1.setCode(tigerPayRequestResponse.getStatusCode())
                        .setMessage(tigerPayRequestResponse.getMessage());
                if (0 == tigerPayRequestResponse.getStatus()) {
                    payRequestLogEntity1.setPayOrderId(IdUtils.genId() + "")
                            .setCode(tigerPayRequestResponse.getStatus() + "")
                            .setPayOrderId(tigerPayRequestResponse.getData().getOrderNo())
                            .setPayUrl(tigerPayRequestResponse.getData().getPayUrl());

                    payRequestLogDao.updateByPrimaryKey(payRequestLogEntity1);
                    PayUrlResponse payUrlResponse = new PayUrlResponse()
                            .setJumpUrl(tigerPayRequestResponse.getData().getPayUrl());
                    return new OpenApiResponse(200, "success").setData(payUrlResponse);
                }

            } catch (IOException e) {
                LOGGER.error(e.getMessage(), e);
            }

            LOGGER.info("==tigerpay 请求支付链接 sign ==,request2:{}", JSON.toJSON(param));
        } catch (Exception e) {
            LOGGER.error("==tigerpay 请求支付链接 sign 异常==", e);
            return new OpenApiResponse(400, "start repayment exception");
        }


        return new OpenApiResponse(400, "create repayment link failed");
    }

    private PaymentParam getCreateParam(PayRequestLogEntity payRequestLogEntity) {
        PaymentParam param = new PaymentParam();
        param.setMerchantNo(productId);
        param.setOutTradeNo(payRequestLogEntity.getOrderNo());
        param.setAmount(payRequestLogEntity.getOrderAmount().longValue() + "");
        param.setName(payRequestLogEntity.getUserName());
//        param.setPhone(payRequestLogEntity.getTel());
        String mobile = payRequestLogEntity.getTel();
        param.setPhone(mobile.substring(0, 4) + "***" + mobile.substring(7));
        param.setEmail("no-reply@gmail.com");
        param.setNotifyUrl(notifyUrl);
        param.setCurrency("INR");
        String sign = MD5SignUtil.digestResData(param, tigerPayKey);//才能够商户后台获取支付秘钥
//        String sign = MD5SignUtil.digestResData(param, "oCecBIpQCEMIKmaxH23iQMEaCFSvyD38");//才能够商户后台获取支付秘钥
        param.setSign(sign);
        return param;
    }


    //支付异步回调

    @RequestMapping("/pay/callback")
    public String payCallBack(@RequestBody TigerPayCallBackRequest request) {
        LOGGER.info("==tigerpay 回调 ==,request1:{}", JSON.toJSON(request));
        try {
            PayCallbackLogEntity payCallbackLogEntity = new PayCallbackLogEntity()
                    .setCode(Integer.valueOf(request.getStatus()))
                    .setMchId(request.getMerchantNo())
                    .setTradeNo(request.getOutTradeNo())
                    .setProductId(Integer.valueOf(request.getMerchantNo()))
                    .setOrderAmount(new BigDecimal(request.getFactAmount()))
                    .setPayOrderId(request.getOrderNo())
                    .setPaySuccessTime(request.getCreateTime())
                    .setMessage(request.getStatus())
                    .setExtra(request.getStatus());

            payCallbackLogDao.insert(payCallbackLogEntity);
            LOGGER.info("==tigerpay 回调  payCallBack success ==");
        } catch (Exception e) {
            LOGGER.error("==tigerpay 回调 payCallBack ==", e);
            return "FAILED";
        }
        return "SUCCESS";
    }


    //同步给催收，还款成功
    public void tellCollectionPaid() {

    }

}
